package com.spark.incoicings.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spark.incoicings.dao.DemandMapper;
import com.spark.incoicings.service.DemandService;
import com.spark.incoicings.vo.DemandVo;
import com.spark.invoicings.entity.Demand;
import com.spark.invoicings.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class DemandServiceImpl extends ServiceImpl<DemandMapper, Demand> implements DemandService {

    @Resource
    private DemandMapper demandMapper;

    /**
     * selectDemandAll 模糊查询所有采购需求
     * selectDemandVo 根据查询的采购需求id获取字典的采购状态和类型
     * @param map
     * @return
     */
    @Override
    public List<Demand> selectDemandAll(Map<String, Object> map) {
        List<Demand> list = demandMapper.selectDemandAll(map);
        list.forEach(demand -> {
            DemandVo demandVo = demandMapper.selectDemandVo(demand.getDemandId());
            demand.setD1status(demandVo.getD1status());
            demand.setD2type(demandVo.getD2type());
        });
        return list;
    }

    /**
     * 根据id更新数据
     * @param demand
     * @return
     */
    @Override
    public boolean updateDemandById(Demand demand) {
        UpdateWrapper<Demand> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("demand_id", demand.getDemandId());
        return update(demand, updateWrapper);
    }

    /**
     * 保存数据
     * @param demand
     * @return
     */
    @Override
    public Result addDemand(Demand demand) {
        // 计算总金额
        demand.setExpectedTotalAmount(demand.getExpectedUnitPrice() * demand.getDemandAmount());
        demand.setCreator(demand.getApplicant());
        demand.setModifier(demand.getApplicant());
        demand.setCreateTime(new Date());
        demand.setModifyTime(new Date());
        demand.setLastActivityTime(new Date());
        demandMapper.insert(demand);
        return Result.success(200, "success", demand.getDemandId());
    }

    /**
     * 根据id获取采购需求
     * @param demandId
     * @return
     */
    @Override
    public Demand selectDemandById(Integer demandId) {
        return demandMapper.selectDemandById(demandId);
    }
}
